<?php

namespace Frontend\Forms;

use DuAdmin\Core\BizException;
use DuAdmin\Helpers\MailHelper;
use Yii;
use Frontend\Models\User;
use yii\base\Model;

class ResendVerificationEmailForm extends Model
{
    /**
     * @var string
     */
    public $email;

    public $captcha;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            [
                'email', 'exist',
                'targetClass' => User::class,
                'filter' => ['status' => User::STATUS_INACTIVE],
                'message' => 'There is no user with this email address.'
            ],
            ['captcha', 'trim'],
            ['captcha', 'required'],
            [
                'captcha',
                'captcha'
            ]
        ];
    }
    public function attributeLabels()
    {
        return [
            'email' => Yii::t('app_user', 'Email'),
            'captcha' => Yii::t('app_user', 'Captcha'),
        ];
    }
    /**
     * Sends confirmation email to user
     *
     * @return bool whether the email was sent
     */
    public function sendEmail()
    {
        $user = User::findOne([
            'email' => $this->email,
            'status' => User::STATUS_INACTIVE
        ]);

        if ($user === null) {
            return false;
        }


        $user->generateEmailVerificationToken();

        $rst = $user->save() && $this->proccessEmail($user);
        if ($user->hasErrors()) {
            Yii::error($user->errors);
            throw new BizException("处理失败");
        }
        return $rst;
    }

    /**
     * Sends confirmation email to user
     * @param User $user user model to with email should be send
     * @return bool whether the email was sent
     */
    protected function proccessEmail($user)
    {
        $template = MailHelper::getMailContent('sys_signup_verify_mail', [
            '{username}' => $user->username,
            '{verifyLink}' => Yii::$app->urlManager->createAbsoluteUrl([
                '/signup/verify-email', 'token' => $user->verificationToken
            ])
        ]);
        return MailHelper::sendEmail(
            [getenv('MAIL_USERNAME') => getenv('MAIL_ALIAS')],
            $user->email,
            $template['title'],
            $template['content']
        );
    }
}
